package restful;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;

import restful.domain.SimplePOJO;
import restful.domain.SimplePOJOList;

/** 
 * Need to configure Jersey JSON procesor itself. 
 * Various configuration options could be set on an JSONConfiguration instance. 
 * The instance could be then further used to create a JSONConfigurated JSONJAXBContext, which serves as a main configuration point in this area. 
 * To pass your specialized JSONJAXBContext to Jersey, you will finally need to implement a JAXBContext ContextResolver
 * 
 * @author Damon
 *
 */

@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {

	private JAXBContext context;
	private Class[] types = {SimplePOJOList.class, SimplePOJO.class};
	
	/**
	 * With natural notation, Jersey will automatically figure out how individual items need to be processed, 
	 * so that you do not need to do any kind of manual configuration. Java arrays and lists are mapped into JSON arrays, 
	 * even for single-element cases. Java numbers and booleans are correctly mapped into JSON numbers and booleans
	 * 
	 * @throws JAXBException
	 */
	public JAXBContextResolver() throws JAXBException {
		this.context = new JSONJAXBContext(JSONConfiguration.natural().rootUnwrapping(false).build(), types);
		System.out.println("---------------------- JAXBContextResolver -----------------------------------");
	}
	
	public JAXBContext getContext(Class<?> objectType) {
		for (Class type : types) {
			if (type == objectType) {
				return context;
			}
		}
		return null;
	}

}
